package com.weitu.base.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weitu.base.constant.DictionaryTypeDefConstants;
import com.weitu.configProperties.ConfigPropertyUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;


public class ConstantInitServlet extends HttpServlet {

	private String[] constantClass={"com.weitu.base.constant.DictionaryTypeDefConstants"};
	private String doc = "var CONSTANT = \"";

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		JSONObject classNameObject=new JSONObject();//常量类
		try{

			//遍历常量类
			for (String className:constantClass){
				Object object= Class.forName(className).newInstance();
				//获取常量属性
				Field[] fields=object.getClass().getFields();
				JSONObject jsonObject=new JSONObject();
				for (Field field:fields){//获取常量名、常量值
					String fieldName=field.getName();
					String fieldValue=((field.get(object.getClass().newInstance())!=null)?field.get(object.getClass().newInstance()).toString():"");
					jsonObject.put(fieldName,fieldValue);
				}

				//获取类名
				String classTypeName=object.getClass().getName();
				if (classTypeName!=null&&!"".equals(classTypeName)){
					classTypeName=classTypeName.substring(classTypeName.lastIndexOf(".")+1,classTypeName.length());
				}
				classNameObject.put(classTypeName,jsonObject);
			}

		}catch (Exception e){
			e.printStackTrace();
		}
		String proString="{}";
		if(classNameObject!=null){
			proString=JSON.toJSONString(classNameObject);
		}
		doc = "var CONSTANT = " + proString + "\n\t";

	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setHeader("Content-Type", "application/javascript");

		resp.getOutputStream().write(doc.getBytes());
	}

}
